package com.ruoyi.generator.controller;

import com.ruoyi.generator.config.FileStorageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileUploadController {

    private final String uploadDir = "E:/fctextjavaworkspace/ruoyiUpload";

    @Autowired
    private FileStorageProperties fileStorageProperties;


    @PostMapping("/api/common/upload")
    public ResponseEntity<Map<String, Object>> handleFileUpload(@RequestParam("file") MultipartFile[] files) {
        Map<String, Object> response = new HashMap<>();

        if (files.length == 0) {
            response.put("status", HttpStatus.BAD_REQUEST.value());
            response.put("message", "未选择文件");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }

        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                response.put("status", HttpStatus.BAD_REQUEST.value());
                response.put("message", "空文件: " + file.getOriginalFilename());
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            try {
                // 保存文件
                File uploadFile = new File(fileStorageProperties.getUploadDir(), file.getOriginalFilename());
                file.transferTo(uploadFile);

                // 添加文件路径到响应中，如果有需要的话
                response.put("fileUrl", fileStorageProperties.getUploadDir() + "/" + file.getOriginalFilename());  // 修改为你的文件实际访问路径

            } catch (IOException e) {
                response.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
                response.put("message", "上传失败: " + e.getMessage());
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        }

        response.put("status", HttpStatus.OK.value());
        response.put("message", "文件上传成功");
        return ResponseEntity.ok(response);
    }
}